﻿package com.sgcc.nfc.lock.presentation.rooms

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.model.Room
import com.sgcc.nfc.lock.domain.usecase.DeleteRoomUseCase
import com.sgcc.nfc.lock.domain.usecase.GetRoomDetailUseCase
import com.sgcc.nfc.lock.presentation.common.EventFlow
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.launch

@HiltViewModel
class RoomDetailViewModel @Inject constructor(
    private val getRoomDetailUseCase: GetRoomDetailUseCase,
    private val deleteRoomUseCase: DeleteRoomUseCase,
    savedStateHandle: SavedStateHandle
) : ViewModel() {

    private val roomId: Long = savedStateHandle.get<Long>("roomId") ?: 0L

    private val _room = MutableLiveData<Room?>()
    val room: LiveData<Room?> = _room

    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _error = MutableLiveData<String?>()
    val error: LiveData<String?> = _error

    private val _events = EventFlow<RoomDetailEvent>()
    val events = _events.events

    init {
        loadDetail()
    }

    fun loadDetail() {
        viewModelScope.launch {
            _isLoading.value = true
            when (val result = getRoomDetailUseCase(roomId)) {
                is NetworkResult.Success -> {
                    _room.value = result.data
                    _error.value = null
                }
                is NetworkResult.Error -> _error.value = result.message
                NetworkResult.Loading -> _isLoading.value = true
            }
            _isLoading.value = false
        }
    }

    fun deleteRoom() {
        viewModelScope.launch {
            when (val result = deleteRoomUseCase(roomId)) {
                is NetworkResult.Success -> _events.emit(RoomDetailEvent.Deleted)
                is NetworkResult.Error -> _events.emit(RoomDetailEvent.ShowMessage(result.message ?: "Operation failed"))
                NetworkResult.Loading -> Unit
            }
        }
    }

    fun currentRoomId(): Long = roomId
}

sealed class RoomDetailEvent {
    data class ShowMessage(val message: String) : RoomDetailEvent()
    data object Deleted : RoomDetailEvent()
}
